package com.wangsh.train.common.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.stereotype.Component;

/**
 * 	日期时间的工具类
 * @author Wangsh
 */
@Component("dateFormatUtil")
public class DateFormatUtil
{
	/**
	 * 将日期变成字符串
	 * 
	 * @param date
	 * @return
	 */
	public String dateStr(Date date)
	{
		SimpleDateFormat sdf = new SimpleDateFormat(ConstatFinalUtil.DATE_FORMAT);
		return sdf.format(date);
	}
	
	/**
	 * 将日期时间变成字符串
	 * 
	 * @param date
	 * @return
	 */
	public String dateTimeStr(Date date)
	{
		SimpleDateFormat sdf = new SimpleDateFormat(ConstatFinalUtil.DATETIME_FORMAT);
		return sdf.format(date);
	}
	
	/**
	 * 将日期变成字符串
	 * 
	 * @param date
	 * @param pattern 日期时间的格式
	 * @return
	 */
	public String dateStr(Date date,String pattern)
	{
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		return sdf.format(date);
	}
	
	/**
	 * 将日期变成字符串
	 * 
	 * @param date
	 * @return
	 */
	public Date strDate(String now)
	{
		SimpleDateFormat sdf = new SimpleDateFormat(ConstatFinalUtil.DATE_FORMAT);
		try
		{
			return sdf.parse(now);
		} catch (ParseException e)
		{
		}
		return null ; 
	}
	
	/**
	 * 将日期时间变成字符串
	 * 
	 * @param date
	 * @return
	 */
	public Date strDateTime(String now)
	{
		SimpleDateFormat sdf = new SimpleDateFormat(ConstatFinalUtil.DATETIME_FORMAT);
		try
		{
			return sdf.parse(now);
		} catch (ParseException e)
		{
		}
		return null ; 
	}
	
	/**
	 * 将日期变成字符串
	 * 
	 * @param date
	 * @param pattern 日期时间的格式
	 * @return
	 */
	public Date strDate(String now,String pattern)
	{
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		try
		{
			return sdf.parse(now);
		} catch (ParseException e)
		{
		}
		return null ; 
	}
	
	/**
	 * 倒计时
	 * 
	 * @return
	 */
	public String formatTime(long millSecond)
	{
		/* 单位 */
		int secondUnit = 1000;
		int minuteUnit = secondUnit * 60;
		int hourUnit = minuteUnit * 60;
		int dayUnit = hourUnit * 24;

		/* 天 */
		long day = millSecond / dayUnit;
		/* 小时 */
		long hour = (millSecond - day * dayUnit) / hourUnit;
		/* 分钟 */
		long minute = (millSecond - day * dayUnit - hour * hourUnit) / minuteUnit;
		/* 秒 */
		long second = (millSecond - day * dayUnit - hour * hourUnit - minute * minuteUnit) / secondUnit;
		/* 毫秒 */
		long milliSecond = millSecond - day * dayUnit - hour * hourUnit - minute * minuteUnit - second * secondUnit;

		StringBuffer sb = new StringBuffer();
		if (day > 0)
		{
			sb.append(day + "天");
		}
		if (hour > 0)
		{
			sb.append(hour + ":");
		}
		if (minute > 0)
		{
			sb.append(minute + ":");
		}
		if (second > 0)
		{
			sb.append(second + ":");
		}
		sb.append(milliSecond);
		return sb.toString();
	}
}
